import 'dart:typed_data';

import 'package:bluetooth_protocols_parser_plugin/library.dart';
import 'package:flutter/foundation.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_file.dart';
import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_status.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../config/const.dart';
import '../../custom_exception/lx_exception.dart';
import '../../l10n/local.dart';
import '../../service/vehicle_connection_service.dart';
import '../../service/global_service.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_battery_info.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_all_info.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_error.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_info.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_settings.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_statistics_once.dart';
import '../../service/realtime_data_server/vehicle_realtime_data/vehicle_statistics_total.dart';
import '../../utils/temp_path_util.dart';
import '../../utils/utils.dart';
import '../models/firmware_info_model.dart';

mixin ProtocolMixin {
  // MARK: 身份identifier，Lorin协议暂不使用（Huari协议需要使用）
  Uint8List get _identifierBytes {
    return GlobalService.to.identifierBytes;
  }

  // MARK: 监听蓝牙通知
  void protocolMixinListenBluetoothNotifyStream(
    Function(Map<String, dynamic>) callback,
  ) {
    VechileConnectionService.to.protocol!.listenBluetoothNotifyStream(
        callbackRealtimeAllInfo: (p0) {
      callback(p0.toMap());
    });
  }

  // MARK: 取消监听蓝牙通知
  void protocolMixinCancelListenBluetoothNotifyStream() {
    VechileConnectionService.to.protocol!.cancelBluetoothNotifyStream();
  }

  // MARK: 写入激活时间
  Future<bool> protocolMixinWriteActiveTime() {
    Uint8List activeTime = Utils.int32ToBytes(TimeUtil.getSecondStamp());
    return VechileConnectionService.to.protocol!.writeActiveTime(activeTime);
  }

  // MARK: 获取设备sn
  Future<String> protocolMixinGetSn() {
    return VechileConnectionService.to.protocol!.getSn().then((rsp) => rsp.data2Text);
  }

  // MARK: 获取产品模型
  Future<String> protocolMixinGetProductModel() {
    return VechileConnectionService.to.protocol!
        .getProductModel()
        .then((rsp) => Utils.uint8List2HexString(rsp.data));
  }

  // MARK: 获取固件版本
  Future<List<FirmwareInfoModel>> protocolMixinGetFirmwareVersion() {
    return VechileConnectionService.to.protocol!.getFirmwareVersion().then(
        (rsp) => rsp.map((item) => FirmwareInfoModel.fromMap(item)).toList());
  }

  // MARK: 建立安全连接
  Future<bool> protocolMixinBuildSafeConnection() {
    return VechileConnectionService.to.protocol!.buildSafeConnection();
  }

  // MARK: 设置周期性数据上报间隔，单位 100ms
  Future<bool> protocolMixinSetPeriodicDataReportingInterval(int interval) {
    return VechileConnectionService.to.protocol!
        .setPeriodicDataReportingInterval((interval).toInt());
  }

  // MARK: 获取综合产品型号
  Future<Map<String, dynamic>> bluetoothHelperGetIntegratedProductInfo() {
    return VechileConnectionService.to.protocol!
        .getIntegratedProductInfo()
        .then((rsp) => rsp.toMap());
  }

  // MARK: 获取综合实时信息全部
  Future<Map<String, dynamic>> protocolMixinGetIntegratedRealtimeInfoAll() {
    return VechileConnectionService.to.protocol!
        .getIntegratedRealtimeInfoAll()
        .then((rsp) => rsp.toMap());
  }

  // MARK: 获取实时信息
  Future<VehicleRealtimeAllInfo> protocolMixinGetRealtimeAll() {
    return VechileConnectionService.to.protocol!
        .getRealtimeAll()
        .then((rsp) => VehicleRealtimeAllInfo.fromMap(rsp.toMap()));
  }

  // MARK: 获取实时信息
  Future<VehicleRealtimeInfo> protocolMixinGetRealtimeInfo() {
    return VechileConnectionService.to.protocol!
        .getRealtimeInfo()
        .then((rsp) => VehicleRealtimeInfo.fromMap(rsp.toMap()));
  }

  // MARK: 获取实时状态
  Future<VehicleRealtimeStatus> protocolMixinGetRealtimeStatus() {
    return VechileConnectionService.to.protocol!
        .getRealtimeStatus()
        .then((rsp) => VehicleRealtimeStatus.fromMap(rsp.toMap()));
  }

  // MARK: 获取实时错误
  Future<VehicleRealtimeError> protocolMixinGetRealtimeError() {
    return VechileConnectionService.to.protocol!
        .getRealtimeError()
        .then((rsp) => VehicleRealtimeError.fromMap(rsp.toMap()));
  }

  // MARK: 获取电池实时信息
  Future<VehicleBatteryInfo> protocolMixinGetRealtimeBatteryInfo() {
    return VechileConnectionService.to.protocol!
        .getRealtimeBatteryInfo()
        .then((rsp) => VehicleBatteryInfo.fromMap(rsp.toMap()));
  }

  // MARK: 获取综合设置
  Future<VehicleSettings> protocolMixinGetSettingsAll() {
    return VechileConnectionService.to.protocol!
        .getSettingsAll()
        .then((rsp) => VehicleSettings.fromMap(rsp.toMap()));
  }

  // MARK: 获取单次统计数据
  Future<VehicleStatisticsOnce> protocolMixinGetStatisticsOnce({
    int? startIndex,
    int? count,
  }) {
    return VechileConnectionService.to.protocol!
        .getStatisticOnce(startIndex: startIndex, count: count)
        .then((rsp) => VehicleStatisticsOnce.fromMap(rsp.toMap()));
  }

  // MARK: 获取总统计数据
  Future<VehicleStatisticsTotal> protocolMixinGetStatisticsTotal() {
    return VechileConnectionService.to.protocol!
        .getStatisticsTotal()
        .then((rsp) => VehicleStatisticsTotal.fromMap(rsp.toMap()));
  }

  // MARK: 锁车
  Future<bool> protocolMixinLock() {
    return VechileConnectionService.to.protocol!
        .lock(_identifierBytes, true)
        .then((rsp) => rsp.isSuccess);
  }

  // MARK: 解锁
  Future<bool> protocolMixinUnlock() {
    return VechileConnectionService.to.protocol!
        .lock(_identifierBytes, false)
        .then((rsp) => rsp.isSuccess);
  }

  // MARK: 鸣笛
  Future<bool> protocolMixinHorn() {
    return VechileConnectionService.to.protocol!.horn();
  }

  // MARK: 开灯
  Future<bool> protocolMixinLight({
    required bool lowBeam,
    required bool highBeam,
  }) {
    return VechileConnectionService.to.protocol!
        .light(lowBeam: lowBeam, highBeam: highBeam);
  }

  // MARK: 获取车辆昵称
  Future<String> protocolMixinGetVehicleNickname() {
    return VechileConnectionService.to.protocol!.getVehicleNickname();
  }

  // MARK: 修改车辆昵称
  Future<bool> protocolMixinChangeVehicleNickname(String? nickname) {
    if (nickname != null && nickname.isNotEmpty) {
      if (Utils.isNotChinese(nickname)) {
        return VechileConnectionService.to.protocol!.setVehicleNickname(nickname);
      }
      throw LxException(local.modify_vehicle_nickname_invalid);
    }
    throw LxException(local.modify_vehicle_nickname_empty);
  }

  // MARK: 获取车辆密码
  Future<String?> protocolMixinGetVehiclePassword() {
    return VechileConnectionService.to.protocol!.getVehiclePassword();
  }

  // MARK: 修改车辆密码
  Future<bool> protocolMixinChangeVehiclePassword(String? newPassword) {
    // 校验是不是纯数字，某则提示错误
    if (newPassword != null &&
        Utils.isNumeric(newPassword) &&
        newPassword.length == vehiclePasswordLength) {
      return VechileConnectionService.to.protocol!.setVehiclePassword(newPassword);
    }
    throw LxException(local.vehicle_password_invalid);
  }

  // MARK: 设置限速翘板，单位 1km/h
  Future<bool> protocolMixinSetSpeedLimitTiltBack(double limitSpd) {
    // 单位转换为 0.01km/h
    return VechileConnectionService.to.protocol!
        .setSpeedLimit((limitSpd.round() * 100).toInt());
  }

  // MARK: 设置限速警告，单位 0.01km/h
  Future<bool> protocolMixinSetSpeedLimitWarning(double warningSpd) {
    return VechileConnectionService.to.protocol!
        .setWarningSpeed((warningSpd.round() * 100).toInt());
  }

  // MARK: 设置骑行模式
  Future<bool> protocolMixinSetRidingMode(int mode) {
    return VechileConnectionService.to.protocol!.setRideMode(mode);
  }

  // MARK: 开启/关闭 骑行辅助
  Future<bool> protocolMixinSetRideAssistSwitch(bool enable) {
    return VechileConnectionService.to.protocol!.setRideAssistSwitch(enable);
  }

  // MARK: 设置加、减速辅助百分比
  Future<bool> protocolMixinSetAccAndBrakeAssistPercentage(
      int accAssist, int brakeAssist) {
    return VechileConnectionService.to.protocol!
        .setAccAndBrakeAssistPercentage(accAssist, brakeAssist);
  }

  // MARK: 设置踏板灵敏度
  Future<bool> protocolMixinSetPedalSensitivity(
      int sensitivity1, int sensitivity2) {
    return VechileConnectionService.to.protocol!
        .setPedalSensitivity(sensitivity1, sensitivity2);
  }

  // MARK: 设置平衡角度
  Future<bool> protocolMixinSetBalanceAngle(int angle) {
    return VechileConnectionService.to.protocol!.setBalanceAngle(angle);
  }

  // MARK: 设置赛道倾斜角
  Future<bool> protocolMixinSetBermAngleModeSwitch(bool enable) {
    return VechileConnectionService.to.protocol!.setBermAngleModeSwitch(enable);
  }

  // MARK: 设置防飞转
  Future<bool> protocolMixinSetSpinKillSwitch(bool enable) {
    return VechileConnectionService.to.protocol!.setSpinKillSwitch(enable);
  }

  // MARK: 设置主声浪
  Future<bool> protocolMixinSetMainSoundSwitch(bool enable) {
    return VechileConnectionService.to.protocol!.setMainSoundSwitch(enable);
  }

  // MARK: 设置语音
  Future<bool> protocolMixinSetVoiceSwitch(bool enable) {
    return VechileConnectionService.to.protocol!.setVoiceSwitch(enable);
  }

  // MARK: 设置待机时长
  Future<bool> protocolMixinSetStandByTime(int time) {
    return VechileConnectionService.to.protocol!.setStandyTime(time);
  }

  // MARK: 设置音量大小百分比
  Future<bool> protocolMixinSetSoundVolume(int volume) {
    return VechileConnectionService.to.protocol!.setVolume(volume);
  }

  // MARK: 设置运输模式
  Future<bool> protocolMixinSetTransportModeSwitch(bool enable) {
    return VechileConnectionService.to.protocol!.setTransportModeSwitch(enable);
  }

  // MARK: 车辆校正
  Future<bool> protocolMixinTriggerVehicleCalibration(
      VehicleCalibrationType type) {
    return VechileConnectionService.to.protocol!.triggerVehicleCalibration(type);
  }

  // MARK: 查询车辆校正状态
  Future<VehicleCalibrationStatus> protocolMixinQueryVehicleCalibrationStatus(
      VehicleCalibrationType type) {
    return VechileConnectionService.to.protocol!.getVehicleCalibrationStatus(type);
  }

  // MARK: 空载检测
  Future<bool> protocolMixinTriggerNoLoadDetection() {
    return VechileConnectionService.to.protocol!.triggerNoLoadDetection();
  }

  // MARK: 载重检测
  Future<bool> protocolMixinTriggerLoadDetection() {
    return VechileConnectionService.to.protocol!.triggerLoadDetection();
  }

  // MARK: 启动电机自适应
  Future<bool> protocolMixinTriggerMotorSelfAdjustment() {
    return VechileConnectionService.to.protocol!.startMotorAdaptation();
  }

  // MARK: 查询电机自适应状态
  Future<MotorAutoStatus> protocolMixinQueryMotorSelfAdjustmentStatus() {
    return VechileConnectionService.to.protocol!.getMotorAdaptationStatus();
  }

  // MARK: 停止电机自适应
  Future<bool> protocolMixinStopMotorSelfAdjustment() {
    return VechileConnectionService.to.protocol!.stopMotorAdaptation();
  }

  // MARK: 清除电机自适应数据
  Future<bool> protocolMixinClearMotorSelfAdjustmentData() {
    return VechileConnectionService.to.protocol!.clearMotorAdaptationData();
  }

  // MARK: 启动电机自检
  Future<bool> protocolMixinTriggerMotorSelfCheck() {
    return VechileConnectionService.to.protocol!.startMotorSelfCheck();
  }

  // MARK: 查询电机自检状态
  Future<bool> protocolMixinQueryMotorSelfCheckStatus() {
    VechileConnectionService.to.protocol!.getMotorSelfCheckResult();
    return Future.value(true);
  }

  // MARK: 开启电池电压校准
  Future<bool> protocolMixinStartBatteryVoltageCalibration() {
    return VechileConnectionService.to.protocol!.startBatteryVoltageCalibration();
  }

  // MARK: 开始OTA固件升级
  Future<void> protocolMixinStartOTA(
    String downloadFirmwareUrl,
    String newVersion,
    TargetDeviceType targetDeviceType, {
    Function(int)? onTotalSize,
    required Function(double) onDownloadProgress,
    required Function(double) onTransferProgress,
    required Function(OtaUpgradeStatus) onStatus,
    required WaitingUserActionCallback onUserActionRequired,
    required int maxMtu,
  }) {
    onStatus.call(OtaUpgradeStatus.started);
    return TempPathUtil.generateTempFilePath().then((savePath) {
      onStatus.call(OtaUpgradeStatus.startDownloading);
      return ApiHelper().downloadFile(
        downloadFirmwareUrl,
        savePath,
        onReceiveProgress: (count, total) {
          onDownloadProgress.call(total > 0 ? count / total * 100 : 0);
          if (count < total) {
            onStatus.call(OtaUpgradeStatus.downloadingFirmware);
          }
        },
      ).then((downloadSuccess) {
        if (downloadSuccess) {
          onStatus.call(OtaUpgradeStatus.downloadSuccess);
          // 下载完成，开始升级并返回其 Future 以便错误能够被上传到调用者
          return VechileConnectionService.to.protocol!.startOTA(
            targetDeviceType,
            savePath,
            newVersion,
            onTotalSize,
            onTransferProgress,
            onStatus,
            onUserActionRequired,
            maxPacketSize: maxMtu,
          );
        } else {
          onStatus.call(OtaUpgradeStatus.downloadFailed);
          return Future.value();
        }
      });
    });
  }

  // MARK: 取消OTA固件升级
  Future<void> protocolMixinCancelOTA({TargetDeviceType? targetDeviceType}) {
    // 如果指定了设备类型，则只停止对应设备的OTA升级，否则停止所有设备的OTA升级
    if (targetDeviceType != null) {
      return VechileConnectionService.to.protocol!.stopOTA(targetDeviceType);
    } else {
      List<Future<void>> futures = [];
      for (var type in GlobalService
          .to.currentVehicleModel.value.firmwareInfoList
          .map((e) => e.deviceType)
          .toList()) {
        if (type != null) {
          futures.add(VechileConnectionService.to.protocol!.stopOTA(type));
        }
      }
      return Future.wait(futures).then((_) => Future.value());
    }
  }

  // MARK: 查询强制固件升级状态
  Future<FirmwareForceUpgradeStatus>
      protocolMixinQueryForceFirmwareUpdateStatus(
          {TargetDeviceType? targetDeviceType}) {
    // 如果targetDeviceType为null，则查询所有支持的设备类型的强制升级状态
    return VechileConnectionService.to.protocol!
        .queryForceFirmwareUpdateStatus(targetDeviceType: targetDeviceType);
  }

  // MARK: 清除强制固件升级标记
  Future<bool> protocolMixinClearForceFirmwareUpdateFlag(
      {TargetDeviceType? targetDeviceType}) {
    // 如果targetDeviceType为null，则清除所有支持的设备类型的强制升级标记
    return VechileConnectionService.to.protocol!
        .clearForceFirmwareUpdateStatus(targetDeviceType: targetDeviceType);
  }

  // MARK: 设置TBOX低电唤醒开关
  Future<bool> protocolMixinSetTBoxLowBatteryWakeupSwitch(bool enable) {
    return VechileConnectionService.to.protocol!.setTBoxLowBatteryWakeupSwitch(enable);
  }

  // MARK: 重启TBOX
  Future<bool> protocolMixinRebootTBox() {
    return VechileConnectionService.to.protocol!.rebootTBox();
  }

  // MARK: 设置TBOX信息显示开关
  Future<bool> protocolMixinSetTBoxInfoDisplaySwitch(bool enable) {
    return VechileConnectionService.to.protocol!.setTBoxInfoDisplaySwitch(enable);
  }

  // MARK: 获取TBOX设备信息
  Future<TBoxInfoModel> protocolMixinGetTBoxDeviceInfo() {
    return VechileConnectionService.to.protocol!.getTBoxInfoModel();
  }

  // MARK: 获取TBOX实时信息
  Future<TBoxRealtimeDataResponse> protocolMixinGetTBoxRealtimeInfo() {
    return VechileConnectionService.to.protocol!.getTBoxRealtimeInfo();
  }

  // MARK: 获取TBOX ESIM 列表
  Future<List<EsimModel>> protocolMixinGetTBoxESIMList() {
    return VechileConnectionService.to.protocol!.getTBoxEsimList();
  }
}
